package tomcat;

import http.HttpRequest;
import http.HttpResponse;
import servlet.IServlet;
import servlet.ServletMappingConfig;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: admin
 * @Description:
 * @Date: 2019/3/19 11:23
 */

public class MyTomcat {
    private int port;
    private Map<String, String> urlServletMap = new HashMap<String, String>();

    public MyTomcat(int port) {
        this.port = port;
    }

    private void initServletMapping() {
        ServletMappingConfig.servletMappingList.forEach(
                servletMapping -> urlServletMap.put(servletMapping.getUrl(), servletMapping.getClazz()));
    }

    private void dispatch(HttpRequest request, HttpResponse response) {
        String clazz = urlServletMap.get(request.getUrl());

        try {
            Class<IServlet> servletClass = (Class<IServlet>) Class.forName(clazz);
            IServlet servlet = servletClass.newInstance();
            servlet.service(request, response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void start() {
        initServletMapping();

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Tomcat is start.... Listening port: " + port);
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                dispatch(new HttpRequest(inputStream), new HttpResponse(outputStream));
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
